package com.jinzhi.eventresource.controller;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.utils.Result;
import com.jinzhi.common.utils.ShiroUtils;
import com.jinzhi.eventresource.main.EventresourceAllocationDO;
import com.jinzhi.eventresource.main.EventresourceAllocationsDO;
import com.jinzhi.eventresource.main.EventresourceModuleDO;
import com.jinzhi.eventresource.main.TemplateCertificateDO;
import com.jinzhi.eventresource.service.EventresourceAllocationService;
import com.jinzhi.eventresource.service.EventresourceAllocationsService;
import com.jinzhi.eventresource.service.EventresourceModuleService;
import com.jinzhi.eventresource.service.TemplateCertificateService;
import com.jinzhi.eventresource.vo.EventresourceAllocationVO;
import com.jinzhi.jzweb.domain.TestPaperTemplateDO;
import com.jinzhi.jzweb.service.ExaminationPaperService;
import com.jinzhi.jzweb.service.TestPaperTemplateService;
import com.jinzhi.sys.domain.UserDO;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.spi.http.HttpHandler;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <pre>
 * 赛项资源模块配置表
 * xzy
 * </pre>
 * <small> 2024-04-03 11:01:14 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/eventresourceAllocation")
public class EventresourceAllocationController extends BaseController {
    @Autowired
    private EventresourceAllocationService eventresourceAllocationService;

    @Autowired
    private EventresourceAllocationsService eventresourceAllocationsService;

    @Autowired
    private ExaminationPaperService examinationPaperService;

    @Autowired
    private EventresourceModuleService eventresourceModuleService;

    @Autowired
    private TestPaperTemplateService testPaperTemplateService;
    @Autowired
    private TemplateCertificateService templateCertificateService;

    @GetMapping()
    @RequiresPermissions("jzweb:eventresourceAllocation:eventresourceAllocation")
    String EventresourceAllocation() {
        return "eventresource/eventresourceAllocation/eventresourceAllocation";
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("jzweb:eventresourceAllocation:eventresourceAllocation")
    public Result<Page<EventresourceAllocationDO>> list(EventresourceAllocationDO eventresourceAllocationDTO) {
        EntityWrapper<EventresourceAllocationDO> wrapper = new EntityWrapper<>();
        wrapper.like(StrUtil.isNotBlank(eventresourceAllocationDTO.getEventName()), "event_name", eventresourceAllocationDTO.getEventName());
        wrapper.eq(ObjectUtil.isNotNull(eventresourceAllocationDTO.getJzEveMoId()), "jz_eve_mo_id", eventresourceAllocationDTO.getJzEveMoId());
        wrapper.orderBy("createTime", false);
        // 查询列表数据
        Page<EventresourceAllocationDO> page = eventresourceAllocationService.selectPage(getPage(EventresourceAllocationDO.class),
                wrapper);
        List list = new ArrayList();
        for (int i = 0; i < page.getRecords().size(); i++) {
            EventresourceAllocationDO obj = (EventresourceAllocationDO) page.getRecords().get(i);
            EventresourceAllocationVO eventresourceAllocationVO = new EventresourceAllocationVO();
            BeanUtils.copyProperties(obj, eventresourceAllocationVO);
            if (obj.getJzEveMoId() == 1775402446075265026L) {
                eventresourceAllocationVO.setJzEveMoId("赛项资源");
            } else if (obj.getJzEveMoId() == 1775402520624824321L) {
                eventresourceAllocationVO.setJzEveMoId("1+X证书资源");
            } else if (obj.getJzEveMoId() == 1775402577172430850L) {
                eventresourceAllocationVO.setJzEveMoId("技能培训");
            } else if (obj.getJzEveMoId() == 1775402630247153666L) {
                eventresourceAllocationVO.setJzEveMoId("行业资源");
            } else if (obj.getJzEveMoId() == 1775402307172499457L) {
                eventresourceAllocationVO.setJzEveMoId("金职大讲堂");
            }

            list.add(eventresourceAllocationVO);
        }
        page.setRecords(list);
        return Result.ok(page);
    }

    @GetMapping("/add")
    @RequiresPermissions("jzweb:eventresourceAllocation:add")
    String add() {
        return "eventresource/eventresourceAllocation/add";
    }

    @GetMapping("/edit/{id}")
    @RequiresPermissions("jzweb:eventresourceAllocation:edit")
    String edit(@PathVariable("id") Long id, Model model) {
        EventresourceAllocationDO eventresourceAllocation = eventresourceAllocationService.selectById(id);
        model.addAttribute("eventresourceAllocation", eventresourceAllocation);
        return "eventresource/eventresourceAllocation/edit";
    }

    @Log("添加赛项资源模块配置表")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("jzweb:eventresourceAllocation:add")
    public Result<String> save(EventresourceAllocationDO eventresourceAllocation) {
        if (ObjectUtil.isEmpty(eventresourceAllocation.getEventTitle())) {
            return Result.fail("标题不能为空！");
        }

        UserDO sysUser = ShiroUtils.getSysUser();
        eventresourceAllocation.setCreateBy(sysUser.getUsername());
        eventresourceAllocation.setCreateTime(DateTime.now());

        if (Objects.isNull(eventresourceAllocation.getYear()) || StrUtil.isEmpty(eventresourceAllocation.getYear())) {
            eventresourceAllocation.setYear(String.valueOf(LocalDate.now().getYear()));
        }


        try {
            eventresourceAllocationService.insert(eventresourceAllocation);
        } catch (Exception e) {
            return Result.fail("字数长度限制标题名称50字!");
        }

        return Result.ok();
    }

    @Log("修改赛项资源模块配置表")
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("jzweb:eventresourceAllocation:edit")
    public Result<String> update(EventresourceAllocationDO eventresourceAllocation) {
        if (ObjectUtil.isEmpty(eventresourceAllocation.getEventTitle())) {
            return Result.fail("标题不能为空！");
        }

        if (Objects.isNull(eventresourceAllocation.getYear()) || StrUtil.isEmpty(eventresourceAllocation.getYear())) {
            eventresourceAllocation.setYear(String.valueOf(LocalDate.now().getYear()));
        }

        boolean update = true;
        try {
            update = eventresourceAllocationService.updateById(eventresourceAllocation);
        } catch (Exception e) {
            return Result.fail("字数长度限制50字");
        }
        return update ? Result.ok() : Result.fail();
    }

    @Log("删除赛项资源模块配置表")
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("jzweb:eventresourceAllocation:remove")
    public Result<String> remove(Long id) {
        // 如果存在子资源则不能删除
        EntityWrapper<EventresourceAllocationsDO> wrapper = new EntityWrapper<>();
        wrapper.eq("allocation_id", id);
        List<EventresourceAllocationsDO> allocationsDOList = eventresourceAllocationsService.selectList(wrapper);

        if (allocationsDOList.size() != 0) {
            return Result.fail("存在子资源！不能删除");
        }
        eventresourceAllocationService.deleteById(id);
        return Result.ok();
    }

    @Log("批量删除赛项资源模块配置表")
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("jzweb:eventresourceAllocation:batchRemove")
    public Result<String> remove(@RequestParam("ids[]") Long[] ids) {
        for (Long id : ids) {
            // 如果存在子资源则不能删除
            EntityWrapper<EventresourceAllocationsDO> wrapper = new EntityWrapper<>();
            wrapper.eq("allocation_id", id);
            List<EventresourceAllocationsDO> allocationsDOList = eventresourceAllocationsService.selectList(wrapper);

            if (allocationsDOList.size() != 0) {
                return Result.fail("存在子资源！不能删除");
            }
        }
        eventresourceAllocationService.deleteBatchIds(Arrays.asList(ids));
        return Result.ok();
    }

    /**
     * @auther: ak
     * @Description 获取赛项模板ID
     * @param:
     * @return:
     * @date: 2024/4/10 13:42
     */
    @Log("获取赛项模板ID")
    @GetMapping("/getModelIds")
    @ResponseBody
    public Result<HashMap<Long, String>> getModuleIds() {
        List<EventresourceModuleDO> eventresourceModuleDOS = eventresourceModuleService.selectList(null);
        HashMap<Long, String> map = new HashMap<>();
        for (EventresourceModuleDO eventresourceModuleDO : eventresourceModuleDOS) {
//            if (ObjectUtil.notEqual(eventresourceModuleDO.getId(), 1775402630247153666L) ) {
            map.put(eventresourceModuleDO.getId(), eventresourceModuleDO.getName());
//            }
        }
        return Result.ok(map);
    }

    /**
     * @auther: ak
     * @Description 获取从2020年到目前年份列表
     * @param:
     * @return:
     * @date: 2024/4/10 13:49
     */
    @Log("获取从2020年到目前年份列表")
    @GetMapping("/getYearList")
    @ResponseBody
    public Result<ArrayList<String>> getYearList() {
        ArrayList<String> yearList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        int currentYear = calendar.get(Calendar.YEAR);
        for (int i = 2020; i <= currentYear; i++) {
            yearList.add(String.valueOf(i));
        }
        return Result.ok(yearList);
    }

    @PostMapping("/setImgUrl")
    @ResponseBody
    public Result setImgUrl(@RequestParam("allocationIds[]") Long[] allocationIds, @RequestParam("second") Integer second) {
        for (Long allocationsId : Arrays.asList(allocationIds)) {

//            EntityWrapper<EventresourceAllocationsDO> wrapper = new EntityWrapper<>();
//            wrapper.eq("allocations_id", allocationsId);
//            List<EventresourceAllocationsDO> eventresourceAllocationsDOList = eventresourceAllocationsService.selectList(wrapper);
//            eventresourceAllocationsDOList.forEach(eventresourceAllocationsDO -> {
//                if (ObjectUtil.isNotEmpty(eventresourceAllocationsDO.getMp4url())
//                        && ObjectUtil.equal(eventresourceAllocationsDO.getMp4url().substring(eventresourceAllocationsDO.getMp4url().lastIndexOf(".")), ".mp4")) {
//                    eventresourceAllocationsDO.setImgurl(eventresourceAllocationsDO.getMp4url() +  "?x-oss-process=video/snapshot,t_" +
//                            second + ",f_jpg,w_0,h_0");
//                    eventresourceAllocationsDO.setUpdateTime(DateTime.now());
//                    eventresourceAllocationsDO.setSecond(Long.valueOf(second));
//                    eventresourceAllocationsService.updateById(eventresourceAllocationsDO);
//                }
//            });
            EventresourceAllocationsDO eventresourceAllocationsDO = eventresourceAllocationsService.selectById(allocationsId);
            if (ObjectUtil.isNotEmpty(eventresourceAllocationsDO.getMp4url())
                    && ObjectUtil.equal(eventresourceAllocationsDO.getMp4url().substring(eventresourceAllocationsDO.getMp4url().lastIndexOf(".")), ".mp4")) {
                eventresourceAllocationsDO.setImgurl(eventresourceAllocationsDO.getMp4url() + "?x-oss-process=video/snapshot,t_" +
                        second + ",f_jpg,w_0,h_0");
                eventresourceAllocationsDO.setUpdateTime(DateTime.now());
                eventresourceAllocationsDO.setSecond(Long.valueOf(second));
                eventresourceAllocationsService.updateById(eventresourceAllocationsDO);
            }
        }
        return Result.ok();
    }


    @GetMapping("/getPaperModuleList")
    @ResponseBody
    public Result<HashMap<Long, String>> paperModuleList() {
        Wrapper<TemplateCertificateDO> wrapper = new EntityWrapper<TemplateCertificateDO>()
                .eq("state", 0)
                .orderBy("id", false);
        List<TemplateCertificateDO> testPaperTemplateDOS = templateCertificateService.selectList(wrapper);
        List<TemplateCertificateDO> collect = testPaperTemplateDOS.stream().distinct().collect(Collectors.toList());

        HashMap<Long, String> map = new HashMap<>();
        for (TemplateCertificateDO templateCertificateDO : collect) {
            map.put(templateCertificateDO.getPaperTemplateId(), templateCertificateDO.getName());
        }
        return Result.ok(map);
    }
}
